All files / web/src/app/api/flowchart-workshop/sessions/[id] route.ts

0% Statements 0/163
0% Branches 0/1
0% Functions 0/1
0% Lines 0/163

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164                                                                                                                                                                                                                                                                                                                                       
import { and, eq } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { db, schema } from '@/db'
import { getUserId } from '@/lib/viewer'

/**
 * GET /api/flowchart-workshop/sessions/[id]
 * Get a workshop session with full draft content
 *
 * Returns: { session: WorkshopSession } or 404
 */
export const GET = withAuth(async (_request, { params }) => {
  try {
    const { id } = (await params) as { id: string }
    const userId = await getUserId()

    const session = await db.query.workshopSessions.findFirst({
      where: and(eq(schema.workshopSessions.id, id), eq(schema.workshopSessions.userId, userId)),
    })

    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 })
    }

    // Check if expired
    if (session.expiresAt && new Date(session.expiresAt) < new Date()) {
      return NextResponse.json({ error: 'Session has expired' }, { status: 410 })
    }

    // Parse refinement history if present
    let refinementHistory: string[] = []
    if (session.refinementHistory) {
      try {
        refinementHistory = JSON.parse(session.refinementHistory)
      } catch {
        // Ignore parse errors
      }
    }

    return NextResponse.json({
      session: {
        ...session,
        refinementHistory,
      },
    })
  } catch (error) {
    console.error('Failed to fetch workshop session:', error)
    return NextResponse.json({ error: 'Failed to fetch session' }, { status: 500 })
  }
})

/**
 * PATCH /api/flowchart-workshop/sessions/[id]
 * Update workshop session state or draft content
 *
 * Body: {
 *   state?: 'initial' | 'generating' | 'refining' | 'testing' | 'completed'
 *   topicDescription?: string
 *   draftDefinitionJson?: string
 *   draftMermaidContent?: string
 *   draftTitle?: string
 *   draftDescription?: string
 *   draftEmoji?: string
 *   draftDifficulty?: string
 *   draftNotes?: string
 *   addRefinement?: string - Add to refinement history
 * }
 *
 * Returns: { session: WorkshopSession }
 */
export const PATCH = withAuth(async (request, { params }) => {
  try {
    const { id } = (await params) as { id: string }
    const userId = await getUserId()
    const body = await request.json()

    // Verify ownership
    const existing = await db.query.workshopSessions.findFirst({
      where: and(eq(schema.workshopSessions.id, id), eq(schema.workshopSessions.userId, userId)),
    })

    if (!existing) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 })
    }

    // Check if expired
    if (existing.expiresAt && new Date(existing.expiresAt) < new Date()) {
      return NextResponse.json({ error: 'Session has expired' }, { status: 410 })
    }

    // Build updates
    const updates: Partial<typeof existing> & { updatedAt: Date } = {
      updatedAt: new Date(),
    }

    if (body.state !== undefined) updates.state = body.state
    if (body.topicDescription !== undefined) updates.topicDescription = body.topicDescription
    if (body.draftDefinitionJson !== undefined)
      updates.draftDefinitionJson = body.draftDefinitionJson
    if (body.draftMermaidContent !== undefined)
      updates.draftMermaidContent = body.draftMermaidContent
    if (body.draftTitle !== undefined) updates.draftTitle = body.draftTitle
    if (body.draftDescription !== undefined) updates.draftDescription = body.draftDescription
    if (body.draftEmoji !== undefined) updates.draftEmoji = body.draftEmoji
    if (body.draftDifficulty !== undefined) updates.draftDifficulty = body.draftDifficulty
    if (body.draftNotes !== undefined) updates.draftNotes = body.draftNotes

    // Handle adding to refinement history
    if (body.addRefinement) {
      let history: string[] = []
      if (existing.refinementHistory) {
        try {
          history = JSON.parse(existing.refinementHistory)
        } catch {
          // Ignore
        }
      }
      history.push(body.addRefinement)
      updates.refinementHistory = JSON.stringify(history)
    }

    const [session] = await db
      .update(schema.workshopSessions)
      .set(updates)
      .where(eq(schema.workshopSessions.id, id))
      .returning()

    return NextResponse.json({ session })
  } catch (error) {
    console.error('Failed to update workshop session:', error)
    return NextResponse.json({ error: 'Failed to update session' }, { status: 500 })
  }
})

/**
 * DELETE /api/flowchart-workshop/sessions/[id]
 * Delete/abandon a workshop session
 *
 * Returns: { success: true }
 */
export const DELETE = withAuth(async (_request, { params }) => {
  try {
    const { id } = (await params) as { id: string }
    const userId = await getUserId()

    // Verify ownership
    const existing = await db.query.workshopSessions.findFirst({
      where: and(eq(schema.workshopSessions.id, id), eq(schema.workshopSessions.userId, userId)),
    })

    if (!existing) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 })
    }

    await db.delete(schema.workshopSessions).where(eq(schema.workshopSessions.id, id))

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Failed to delete workshop session:', error)
    return NextResponse.json({ error: 'Failed to delete session' }, { status: 500 })
  }
})